class Solution {
public:
    const static int  N=2*1e5+10;
    int h[N],w[N],ne[N],to[N],idx;
    int dist[4*N],cnt[4*N];
    int n;
    void add(int x,int y,int z)
    {
        ne[idx]=h[x];
        w[idx]=z;
        to[idx]=y;
        h[x]=idx++;
    }
    void spfa()
    {
        memset(dist,-0x3f3f3f,sizeof(dist));
        dist[0]=0;
        queue<int> q;
        q.push(0);
        while(q.size())
        {
            int u=q.front();
            q.pop();
            for(int i=h[u];~i;i=ne[i])
            {
                int j=to[i];
                int z=w[i];
                if(dist[j]<dist[u]+z)
                {
                    dist[j]=dist[u]+z;
                    cnt[j]=cnt[u]+1;
                    q.push(j);
                }
            }
        }
    }
    int candy(vector<int>& ratings) {
        n=ratings.size();
        idx=0;
        memset(h,-1,sizeof(h));
        for(int i=1;i<=n;i++)
        {
            //xi>=0+1
            add(0,i,1);
        }

        for(int i=1;i<n;i++)
        {
            if(ratings[i]>ratings[i-1])
            {
                //xi>=xi-1+1
                add(i,i+1,1);
            }
            else if(ratings[i]<ratings[i-1])
            {
                add(i+1,i,1);
            }

        }
        spfa();
        int ret=0;
        for(int i=1;i<=n;i++)
        {
            ret+=dist[i];
        }
        return ret;
    }
};
